const app = getApp();
const config = require('./config.js');

//  刷新token
function getAccessToken(callback) {
    uni.request({
        url: config.pathAuth + '/login/refreshing-token',
        headers:{
						'Authorization': 'Bearer ' + uni.getStorageSync('access_token'),
				},
        data: {
            clientId: config.clientId,
            clientSecret: config.clientSecret,
        },
        method: 'GET',
        success: function (res) {
					if (res.data.code == 1) {
						let data=res.data.data
							let expiresIn = new Date().getTime() + data.expiresIn * 1000
							uni.setStorageSync('expiresIn', expiresIn); // 处理token过期时间
							// uni.setStorageSync('userName', data.user.name);
							// uni.setStorageSync('accountId', data.user.id);
							
							let accesstoken = data.access_token;
							uni.setStorageSync('access_token', accesstoken);
							
							if (typeof callback === 'function' && accesstoken) {
							    callback(accesstoken);
							}
					}else{ // token刷新失败
						uni.reLaunch({
							url:'/pages/login/login'
						})
						
					}
        }
    });
} // 封装request请求

const myRequest = (options) => {
    // console.log("myRequest",options)
    if (options) {
        console.log("storage=", uni.getStorageSync('access_token'))
        if (uni.getStorageSync('access_token') === '') {
					runRequest('', options)
            // uni.reLaunch({
            // 	url:'/pages/login/login'
            // })
        } else { // 有token
					runRequest(uni.getStorageSync('access_token'), options);
					// if(isTokenExpired()){ // token是否过期 已过期
					// 	getAccessToken(function (accesstoken) { // 刷新token 
					// 	    runRequest(uni.getStorageSync('access_token'), options); // 发起请求
					// 	});
					// }else{
					// 	runRequest(uni.getStorageSync('access_token'), options);
					// }
        }
    }
}; // 执行请求

/*判断token是否过期*/
function isTokenExpired() {
    let expiredTime = new Date().getTime(); // 获取毫秒
    /*从localStorage中取出token过期时间*/
    if (uni.getStorageSync('expiresIn') != undefined && uni.getStorageSync('expiresIn') != "undefined") {
        expiredTime = uni.getStorageSync('expiresIn')  // 获取缓存token过期时间  毫秒
    }
    /*获取本地当前时间戳*/
    let nowTime = new Date().getTime()

    /*如果 < 10分钟，则说明即将过期*/
    var flag = (expiredTime - nowTime) < 10 * 60;

    return flag;
};

function runRequest(token, options) {
    // header 设置Content-Type，token, token, noncestr, timestamp等信息，与后台协商好
    if (options.header === undefined || options.header === null) { 
        options.header = { 
					'content-type': 'application/json' // 默认    application/x-www-form-urlencoded
				}
    }
		// options.header['Access-Control-Allow-Origin'] = 'http://ajxm.anche.com/'
    // if (token) {
    //     options.header['Authorization'] = 'Bearer ' + token;
    // }
    if (options.url.indexOf('http') != 0) {
        // options.url = baseUrl + options.url;
    } // method、data
		// if (!isValidUrl(options.url)) { // 请求路径错误
		// 	options.url = 'http://172.0.0.12:9527';
		// }
		// function isValidUrl(url) {
		//   const regex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(\:[0-9]+)?)(\/[a-zA-Z0-9%_.~+-]+)*\/?(\?[a-zA-Z0-9%_.,~+-=&]*)?(#[a-zA-Z0-9_-]+)?$/;
		//   return regex.test(url);
		// }

    if (options.method === undefined || options.method === null) {
        options.method = 'post';
    }

    if (options.success && typeof options.success === 'function') {
        let successCallback = options.success;

        options.success = function (res) {
            // console.log("result=",res)
            if (res.statusCode === 200) {
                try {
                    //调用自定义的success
                    successCallback(res);
                } catch (e) {
                    // console.error('出错了，' + e + ',接口返回数据:' + res.data);
                }
            } else if (res.statusCode === 401) {
                // token无效，重新获取token
                uni.setStorageSync('access_token', '');
                getAccessToken(function (token) {
                    runRequest(uni.getStorageSync('access_token'), options);
                });
            } else {
                // console.log('返回异常：', res);
                successCallback(res);
            }
        };
    } //执行微信的请求

    uni.request(options);
}

module.exports = {
    myRequest: myRequest
};
